package com.manage.demo.interceptor;

import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.manage.demo.component.Settings;

@Component
public class BaseInterceptor implements HandlerInterceptor{
    
    private static final Logger logger = LogManager.getLogger(BaseInterceptor.class);
    
    @Autowired
    private Settings settings;  // settings.java 秘钥
    private static final Set<String> NOT_INTERCEPT_URI = new HashSet<>();  //不拦截的URI
    // 不拦截
    static {
        NOT_INTERCEPT_URI.add("/login/");
        NOT_INTERCEPT_URI.add("/log_valid");
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
        if (NOT_INTERCEPT_URI.contains(request.getRequestURI())) {
             return true;
         }else {
             Object user = request.getSession().getAttribute("name");
             if (user == null) {
                 //重定向到登录页面
                 response.sendRedirect("http://127.0.0.1:8080/login/?framework=html");
            	 return false;  // 拦截
                 
             }else {
            	 return true;  // 放行
             }
        }
    }
    
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            @Nullable ModelAndView modelAndView) throws Exception {
        logger.info("BaseInterceptor postHandle settings:" + settings);
        logger.info("BaseInterceptor postHandle session:" + request.getSession().getAttribute("user_input"));
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
            @Nullable Exception ex) throws Exception {
        logger.info("BaseInterceptor afterCompletion settings:" + settings);
        logger.info("BaseInterceptor afterCompletion session:" + request.getSession().getAttribute("user_input"));
    }
}
